import { Model, DataTypes, Optional } from 'sequelize';
import { sequelize } from '../config/database';
import User from './User';

export interface MessageAttributes {
    id: string;
    senderId: string;
    receiverId: string;
    content: string;
    type: 'text' | 'image' | 'file';
    status: 'sent' | 'delivered' | 'read';
    createdAt?: Date;
    updatedAt?: Date;
}

export interface MessageCreationAttributes extends Optional<MessageAttributes, 'id' | 'createdAt' | 'updatedAt'> { }

class Message extends Model<MessageAttributes, MessageCreationAttributes> implements MessageAttributes {
    public id!: string;
    public senderId!: string;
    public receiverId!: string;
    public content!: string;
    public type!: 'text' | 'image' | 'file';
    public status!: 'sent' | 'delivered' | 'read';
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

    public static associate(models: any) {
        Message.belongsTo(models.User, {
            foreignKey: 'senderId',
            as: 'sender'
        });
        Message.belongsTo(models.User, {
            foreignKey: 'receiverId',
            as: 'receiver'
        });
    }
}

export const initMessage = (sequelize: any) => {
    Message.init(
        {
            id: {
                type: DataTypes.UUID,
                defaultValue: DataTypes.UUIDV4,
                primaryKey: true
            },
            senderId: {
                type: DataTypes.UUID,
                allowNull: false,
                references: {
                    model: 'users',
                    key: 'id'
                }
            },
            receiverId: {
                type: DataTypes.UUID,
                allowNull: false,
                references: {
                    model: 'users',
                    key: 'id'
                }
            },
            content: {
                type: DataTypes.TEXT,
                allowNull: false
            },
            type: {
                type: DataTypes.ENUM('text', 'image', 'file'),
                defaultValue: 'text'
            },
            status: {
                type: DataTypes.ENUM('sent', 'delivered', 'read'),
                defaultValue: 'sent'
            }
        },
        {
            sequelize,
            modelName: 'Message',
            tableName: 'messages',
            timestamps: true
        }
    );
};

export default Message; 